package com.libinshen.wxpay.login.service.impl;

import com.libinshen.wxpay.common.constant.Constants;
import com.libinshen.wxpay.common.util.common.JwtUtils;
import com.libinshen.wxpay.common.util.wxUtils.WxLoginUtils;
import com.libinshen.wxpay.login.entity.miniapp.AppAuthLoginRespVO;
import com.libinshen.wxpay.login.mapper.UserInfoMapper;
import com.libinshen.wxpay.login.service.WxLoginService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;



@Service("wxLoginService")
public class WxLoginServerImpl implements WxLoginService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private UserInfoMapper userMapper;

    @Override
    public AppAuthLoginRespVO wxLogin(String code) {
        Map<String, String> result = WxLoginUtils.getAccessToken(code);
        //TODO 以下是获取accessToken以及openId 之后的业务逻辑，根据不同的场景实现不同的逻辑。需要优化

        //先根据openid 进行数据库查询是否存在
        AppAuthLoginRespVO appAuthLoginRespVO = userMapper.selectUserByOpenid(result.get("openId"));
        if (appAuthLoginRespVO == null) {
            Map userInfo = WxLoginUtils.getUserInfo(result.get("access_token"), result.get("open_id"));
            String nickname = (String) userInfo.get("nickname");
            String headimgurl = (String) userInfo.get("headimgurl");
            appAuthLoginRespVO.setNickName(nickname);
            appAuthLoginRespVO.setAvatar(headimgurl);
            appAuthLoginRespVO.setOpenid(result.get("openId"));
            appAuthLoginRespVO.setPhone("");
            //将用户信息插入数据库中，我们需要做两张表，关于用户信息，用户社交登陆的信息构建一张表，通过注册方式的手段在建立一张表， 同时在建立一张中间表
            //userMapper.register();
        }

        //微信登录生成的token
        String redisTokenKey = Constants.PERMISSION_WEB_USER_INFO + appAuthLoginRespVO.getId();
        String token = redisTemplate.opsForValue().get(redisTokenKey);
        if (StringUtils.isEmpty(token)) {
            //token过期自动删除或者第一次登陆
            token = JwtUtils.creatToken(Long.valueOf(appAuthLoginRespVO.getId()), new Date());
            //token 在redis的存储时间是12 Hours
            redisTemplate.opsForValue().set(redisTokenKey, token, 12, TimeUnit.HOURS);
        }
        return appAuthLoginRespVO;
    }
}
